package com.servlet;

import com.Service.Impl.UserServiceImpl;
import com.Service.UserService;
import com.Util.IsNotNullUtil;
import com.entity.User;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet("/login")
public class LoginServlet extends HttpServlet {
    private UserService service = new UserServiceImpl();
    //定义一周时长
    public static final int ONE_WEEK = 1000 * 60 * 60 * 24 * 7;

    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //获取前端用户输入的数据
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        //分别获取用户和服务器生成的验证码
        String randomCode = req.getParameter("randomCode");
        String session = req.getSession().getAttribute("RANDOMCODE_IN_SESSION").toString();
        if (!(IsNotNullUtil.isNotNull(randomCode) && IsNotNullUtil.isNotNull(session) && randomCode.equalsIgnoreCase(session))) {
            req.setAttribute("codeMsg","验证码错误");
            req.getRequestDispatcher("/login.jsp").forward(req,resp);
            return;
        }
        try {
            //根据获取到的信息进行查询
            User user = service.checkUser(username, password);
            //当登陆成功后,将账户名存储在Cookie中
            Cookie cookie = new Cookie("username", username);
            //获取页面中记住我的状态,即复选框的checked属性(boolean)
            boolean rememberMe = Boolean.parseBoolean(req.getParameter("rememberMe"));
            //根据rememberMe的判断,设置Cookie的存活时长(存活一周)
            cookie.setMaxAge((rememberMe) ? ONE_WEEK : 0);
            //将设置好存活时长的Cookie响应给浏览器
            resp.addCookie(cookie);
            //将登陆成功的账户,通过会话域共享
            req.getSession().setAttribute("USER_IN_SESSION", user);
            //跳转到展示所有人物信息
            resp.sendRedirect("/shuihu");
        } catch (RuntimeException e) {
            e.printStackTrace();
            req.setAttribute("loginMsg", "账户或密码错误,请重新登陆");
            req.getRequestDispatcher("/login.jsp").forward(req, resp);
        }
    }
}
